﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.MVC.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Common.Helpers;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.DAL.Models.DHQG;
using DHQGHN.DAL.BO.DHQG;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class GroupController : BaseController
    {
        GroupBO appBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(GroupController));

        public ActionResult Index(GroupModel aModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (aModel == null) aModel = new GroupModel();

                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[2] = "active";
                ViewBag.ActiveMenus[30] = "active";
                aModel.IsActive = 2;
                var model = search(aModel, pageIndex, currentId, false);
                ViewBag.lstStatus = getListStatus();
                ViewBag.lstType = getListType();
                ViewBag.lstApp = CommonData.getListApp();
                return View("~/Views/Group/Group.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        private IEnumerable<SelectListItem> getListApp()
        {
            try
            {
                ApplicationBO appBO = new ApplicationBO();
                var lstApp = appBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "0",
                    Text = "Chọn ứng dụng"
                });
                foreach (var type in lstApp)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.AppId.ToString(),
                        Text = type.AppName
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListStatus()
        {
            try
            {
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.AddRange(new[]{
                new SelectListItem() { Text = "Tất cả", Value = "2" },
                new SelectListItem() { Text = "Đang sử dụng", Value = "1" },
                            new SelectListItem() { Text = "Không sử dụng", Value = "0" }
            });
                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        private IEnumerable<SelectListItem> getListType()
        {
            try
            {
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.AddRange(new[]{
                new SelectListItem() { Text = "-- Chọn Loại --", Value = "" },
                new SelectListItem() { Text = "Nhóm quản trị", Value = "A" },
                            new SelectListItem() { Text = "Nhóm nghiệp vụ", Value = "B" }
            });
                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult reActive(int appId)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    GroupModel model = new GroupModel();
                    appBO = new GroupBO();
                    bool result = appBO.reActive(appId);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(), CommonData.AppName,
                            GetFunction(),
                            "GroupId: " + appId,
                            Resources.Localization.ActionActiveCaption + " - reActive");

                        return Json(JsonResponse.Json200("Khôi phục Nhóm người dùng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }
        /// <summary>
        /// Hiển thị form thêm mới người dùng
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        [HttpPost]
        //[CustomAuthorize]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionPrepareCreateOrUpdateGroup(int? appId)
        {
            try
            {
                ViewBag.lstApp = CommonData.getListApp(Resources.Localization.AppText, Resources.Localization.AppTextValue);
                ViewBag.lstType = getListType();
                GroupModel app = null;
                if (appId != null && appId > -1)
                {
                    appBO = new GroupBO();
                    app = new GroupModel(appBO.GetGroupById(appId));

                }
                if (app == null)
                {
                    app = new GroupModel()
                    {
                        GroupName = "",
                        GroupCode = "",
                        Description = "",
                        GroupId = -1,
                        IsActive = 1
                    };
                }
                getNhomCoBan(app.GroupId);
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Group/_GroupModel.cshtml", app);
                }
                //RedirectToAction("ManageUsers", "Admin");
                return View(app);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        private NhomDonViBO _sqlNhomDVBO;
        private void getNhomCoBan(int groupId)
        {
            _sqlNhomDVBO = new NhomDonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            List<NhomDonVi> items = _sqlNhomDVBO.GetNhomDVByType_New(1);
            GroupNhomCoBanBO groupNhomCoBanBO = new GroupNhomCoBanBO();
            List<DHQGHN.DAL.Models.Admin.GroupNhomCoBan> modelList = groupNhomCoBanBO.GetByGroupId(groupId);
            List<SelectListItem> lstNhomDonViCoBan = new List<SelectListItem>();

            for (int i = 0; i < items.Count; i++)
            {
                lstNhomDonViCoBan.Add(new SelectListItem
                {
                    Text = items[i].TenNhomDonVi,
                    Value = items[i].NhomDonViId.ToString()
                });
            }
            for (int i = 0; i < modelList.Count; i++)
            {
                for (int j = 0; j < lstNhomDonViCoBan.Count; j++)
                {
                    if (lstNhomDonViCoBan[j].Value == modelList[i].NhomCoBanId.ToString())
                    {
                        lstNhomDonViCoBan[j].Selected = true;
                    }
                }
            }
            ViewBag.lstNhomDonVi = lstNhomDonViCoBan;

        }

        [HttpPost]
        public ActionResult actionPrepareListRoleByGroupId(int? groupId)
        {
            try
            {
                GroupModel group = null;
                ViewBag.lstRoleByGroupId = getRoleNameByGroupId(groupId);
                ViewBag.lstAppByGroupId = getAppNameByGroupId(groupId);
                ViewBag.lstGroup = getGroupNameByGroupId(groupId);
                ViewBag.lstType = getListType();
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Group/Index.cshtml", group);
                }
                return View(group);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string getGroupNameByGroupId(int? groupId)
        {
            try
            {
                GroupBO groupBO = new GroupBO();
                string lstGroupName = groupBO.GetGroupNameByGroupId(groupId);
                //List<GroupModel> lstItems = new List<GroupModel>();
                //foreach (var group in lstGroupName)
                //{
                //    lstItems.Add(new GroupModel(group));
                //}
                return lstGroupName;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private dynamic getAppNameByGroupId(int? groupId)
        {
            try
            {
                ApplicationBO groupBO = new ApplicationBO();
                var lstAppName = groupBO.GetAppNameByGroupId(groupId);
                List<ApplicationModel> lstItems = new List<ApplicationModel>();
                foreach (var group in lstAppName)
                {
                    lstItems.Add(new ApplicationModel(group));
                }
                return lstItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public List<RoleModel> getRoleNameByGroupId(int? groupId)
        {
            try
            {
                RoleBO userBO = new RoleBO();
                var lstRoleName = userBO.getRoleNameByGroupId(groupId);
                List<RoleModel> lstItems = new List<RoleModel>();
                foreach (var group in lstRoleName)
                {
                    lstItems.Add(new RoleModel(group));
                }
                return lstItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(GroupModel aModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                var model = new DataPage<GroupModel>();
                while (model.Data.Count() == 0 && pageIndex >= 0)
                {
                    model = search(aModel, pageIndex, currentId, false);
                    pageIndex--;
                }
                return PartialView("~/Views/Group/_GroupList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Thêm mới người dùng
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        //[CustomAuthorize]
        [ValidateInput(false)]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionCreateOrUpdateGroup(GroupModel model, int[] nhomDonViCoBan)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    appBO = new GroupBO();
                    bool result = appBO.createOrUpdateGroup(model.toDALModel(), nhomDonViCoBan);
                    if (result)
                    {
                        LogStream.Write<GroupModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption
                            + " - actionCreateOrUpdateGroup", model);

                        if (model.GroupId > -1)
                        {
                            return Json(JsonResponse.Json200("Cập nhật thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] groupList)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    appBO = new GroupBO();
                    bool result = appBO.deleteGroup(groupList);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(groupList),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Ngừng sử dụng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Kiem tra xem ten ung dung da ton tai chua
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="GroupId"> </param>
        /// <returns></returns>
        //[CustomAuthorize]
        //[ValidateJsonAntiForgeryToken]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public JsonResult CheckExistGroupName(string GroupName, int? GroupId)
        {
            try
            {
                GroupModel appModel = new GroupModel()
                {
                    GroupName = GroupName

                };
                var model = searchd(appModel, 0, -1, true);
                var isExist = false;
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (GroupModel app in lstItem)
                    {
                        if (GroupId != null && GroupId > 0)
                        {
                            //Neu chinh sua thong tin ung dung thi chi kiem tra nhung ung dung khac co trung khong
                            if (app.GroupId != GroupId)
                            {
                                isExist = true;
                                break;
                            }
                        }
                        else
                        {
                            //Kiem tra truong hop them moi
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.GroupNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private DataPage<GroupModel> searchd(GroupModel aModel, int pageIndex, int currentId, bool compareEqual)
        {
            try
            {
                appBO = new GroupBO();
                //Binding ListItem
                //BindDataToCcbPeopleType();

                //var model = peopleBo.GetListPaging(pModel, PageSize, page);
                var DALModel = appBO.GetDynamicListPagingd(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var model = new DataPage<GroupModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.GroupModel app in lstItem)
                {
                    model.Data.Add(new GroupModel(app));
                }

                GroupModel appModel = null;
                if (currentId >= 0 && model.Data.Count > 0)
                {
                    appModel = model.Data.Find(user => user.GroupId == currentId);
                    model.CustomData = appModel;
                }
                else
                {
                    model.CustomData = aModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Group",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "app-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Kiem tra xem Ma ung dung da ton tai chua
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="GroupId"> </param>
        /// <returns></returns>
        //[CustomAuthorize]
        //[ValidateJsonAntiForgeryToken]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public JsonResult CheckExistGroupCode(string GroupCode, int? GroupId)
        {
            try
            {
                GroupModel appModel = new GroupModel()
                {
                    GroupCode = GroupCode
                };
                var model = searchd(appModel, 0, -1, true);
                var isExist = false;
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (GroupModel app in lstItem)
                    {
                        if (GroupId != null && GroupId > 0)
                        {
                            //Neu chinh sua thong tin ung dung thi chi kiem tra nhung ung dung khac co trung khong
                            if (app.GroupId != GroupId)
                            {
                                isExist = true;
                                break;
                            }
                        }
                        else
                        {
                            //Kiem tra truong hop them moi
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.GroupCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private DataPage<GroupModel> search(GroupModel aModel, int pageIndex, int currentId, bool compareEqual)
        {
            try
            {
                appBO = new GroupBO();
                //Binding ListItem
                //BindDataToCcbPeopleType();

                //var model = peopleBo.GetListPaging(pModel, PageSize, page);
                var DALModel = appBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var model = new DataPage<GroupModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.GroupModel app in lstItem)
                {
                    model.Data.Add(new GroupModel(app));
                }

                GroupModel appModel = null;
                if (currentId >= 0 && model.Data.Count > 0)
                {
                    appModel = model.Data.Find(user => user.GroupId == currentId);
                    model.CustomData = appModel;
                }
                else
                {
                    model.CustomData = aModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Group",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "app-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch
            {
                throw;
            }
        }

        private string GetFunction()
        {
            return "Quản trị nhóm người dùng - GroupController";
        }
    }
}